package hr.dario.fragments.app;


import hr.dario.fragments.Contact;
import hr.dario.fragments.R;
import hr.dario.fragments.data.DataBaseAdapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.UriBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class LocationsFragment_2 extends ListFragment{
		//implements LoaderManager.LoaderCallbacks<Cursor>{
	private static final int ACTIVITY_DESC = 0;
	private boolean mDualPane;
	private ListView mLv;
	private int mCurCheckPosition = 1;
	private final String TAG = "LOCATIONS_FRAGMENT_TAG";
	private List<Contact> list = new ArrayList<Contact>();
	private DataBaseAdapter mDbHelper;
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
	                                ContextMenuInfo menuInfo) {
	    super.onCreateContextMenu(menu, v, menuInfo);	 
	    
        	Toast.makeText(getActivity(), "Contextual menu pressed",
					Toast.LENGTH_SHORT).show();        	   	   
	}
	
	private static URI getBaseURI() {
		return UriBuilder.fromUri("http://176.28.21.111:8080/KoshnicaService_v1.3").build();
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		
		View view = inflater.inflate(R.layout.locations_fragment_2, container, false);
		
		ClientConfig clientConfig = new DefaultClientConfig();
		Client client = Client.create(clientConfig);
		
		WebResource service = client.resource(getBaseURI());
		
		TextView json = (TextView) view.findViewById(R.id.json_text);
		
		try {

			String myFeed = "http://176.28.21.111:8080/KoshnicaService_v1.3/rest/contacts/palach_001";
			URL url = new URL("http://176.28.21.111:8080/KoshnicaService_v1.3/rest/contacts/");
			Log.i(TAG, "url opend");
			URLConnection connection = url.openConnection();
			
			int responseCode = -1;
			HttpURLConnection httpConnection = null;
			int iRetry = 0;

			while (iRetry < 10) {
				iRetry++;
				try {
					httpConnection = (HttpURLConnection) connection;
					httpConnection.setConnectTimeout(3000);
					httpConnection.setDoInput(true);
					httpConnection.connect();
					responseCode = httpConnection.getResponseCode();
				} catch (IOException e) {
					e.printStackTrace();
					responseCode = -1;
				}
				if (responseCode == HttpURLConnection.HTTP_OK) {
					iRetry = 10;
					Log.i(TAG, "If it came to here web service is working");
					InputStream in = httpConnection.getInputStream();				
				    BufferedReader br = new BufferedReader(new InputStreamReader(in));
				    String jsonString = null;
				  
				    try {
				        // While the BufferedReader readLine is not null 
				    	
				        	jsonString = br.readLine();    
				        // Close the InputStream and BufferedReader
				        	in.close();
				        	br.close();

				    } catch (IOException e) {
				        e.printStackTrace();
				    }
				    
				    json.setText(jsonString);
				    Log.i(TAG,jsonString);
				    JSONObject jsonObject;

				    Log.i(TAG, "1. chekpoint!");
					try {
						Log.i(TAG, "2. chekpoint!");
						jsonObject = new JSONObject(jsonString);	
						Log.i(TAG, "3. chekpoint!");
						JSONArray jsonArray = jsonObject.getJSONArray("contact");
						Log.i(TAG, "4. chekpoint!");
						for (int i = 0; i < jsonArray.length(); i++) {
						    Contact c = new Contact();
						    JSONObject jsonContact = jsonArray.getJSONObject(i);
						    
						    JSONArray jArr2 = jsonContact.getJSONArray("address");
						    jsonObject = jArr2.getJSONObject(1);
						    System.out.println("0: "+jsonObject.getString("city"));
						    
						    
						    c.setId(jsonContact.getString("id"));
						    c.setName(jsonContact.getString("name"));
						    
						    list.add(c);
						    System.out.println("1: "+c.getId());
						    System.out.println("2: "+c.getName());
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				    /*
					DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
							.newInstance();
					DocumentBuilder documentBuilder = documentBuilderFactory
							.newDocumentBuilder();

					Document dom = documentBuilder.parse(in);
					Element documentElement = dom.getDocumentElement();*/
					Log.i(TAG, "doso do kraja!");
					//addAllLocations(documentElement);
				} /*else {
					iRetry = 10;
					Resources myResources = getResources();
					InputStream inputStream = myResources
							.openRawResource(R.raw.service);
					DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
							.newInstance();
					DocumentBuilder documentBuilder = documentBuilderFactory
							.newDocumentBuilder();
					Document document = documentBuilder.parse(inputStream);
					Element documentElement = document.getDocumentElement();
					Log.i(TAG, "doso do kraja!");
					//addAllLocations(documentElement);
				}*/
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		/*} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();*/
		} finally {
		}
		/*System.out.println(
				service.path("rest").
				path("contacts").
				accept(MediaType.APPLICATION_JSON).
				get(String.class));
		
		json.setText(
				service.path("rest").
				path("contacts").
				path("palach_001"). //add contacts id to the path
				accept(MediaType.APPLICATION_JSON).
				get(String.class));
		*/
		mLv = (ListView) view.findViewById(android.R.id.list);
		mLv.setEmptyView(view.findViewById(android.R.id.empty));
		
		return view;
	}
	
	
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mDbHelper = new DataBaseAdapter(getActivity());
		
		
		
		fillData();
		
				
		
		registerForContextMenu(getListView());
		
		View detailsFrame = getActivity().findViewById(R.id.loc_desc_fragment);
		
        mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
  
        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 1);
        }

        if (mDualPane) {
            // In dual-pane mode, the list view highlights the selected item.
            getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
            // Make sure our UI is in the correct state.
            showDetails(mCurCheckPosition);
        }

	}
			  
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    	System.out.println(""+position);
    	showDetails(position+1);
    }

    void showDetails(int index) {
        mCurCheckPosition = index;

        if (mDualPane) {
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            LocDescFragment details = (LocDescFragment)
                    getFragmentManager().findFragmentById(R.id.loc_desc_fragment);
            if (details == null || details.getShownIndex() != index) {
                // Make new fragment to show this selection.
                details = LocDescFragment.newInstance(index);

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.loc_desc_fragment, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), LocDescActivity.class);
            intent.putExtra("index", index);
            //startActivity(intent);
            startActivityForResult(intent, ACTIVITY_DESC);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }
    
	private void fillData() {
		// Get all of the rows from the database and create the item list	
		
		// Create an array to specify the fields we want to display in the list
		// (only TITLE)
		
		ListAdapter adapter = new ContactListAdapter(getActivity(), list,
				R.layout.location_row, new String[] {
		          Contact.KEY_ID, Contact.KEY_NAME }, new int[] {
		          R.id.text1, R.id.text2 });
		    this.setListAdapter(adapter);
		    
		/*    
		String[] from = new String[] { DataBaseAdapter.KEY_LOC_NAME,
				DataBaseAdapter.KEY_LOC_DESCRIPTION };

		// and an array of the fields we want to bind those fields to (in this
		// case just text1)
		int[] to = new int[] { R.id.text1, R.id.text2 };
        
		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter locations = new SimpleCursorAdapter(getActivity(),
				R.layout.location_row, LocationsCursor, from, to);
		setListAdapter(locations);
				*/	
		
				
	}
	
	public class ContactListAdapter extends SimpleAdapter {

		private List<Contact> contacts;
		/*
		* Alternating color list -- you could initialize this from anywhere.
		* Note that the colors make use of the alpha here, otherwise they would be
		* opaque and wouldn't give good results!
		*/
		//private int[] colors = new int[] { 0x30ffffff, 0x30808080 };

		@SuppressWarnings("unchecked")
		public ContactListAdapter(Context context, 
		        List<? extends Map<String, String>> contacts, 
		        int resource, 
		        String[] from, 
		        int[] to) {
		  super(context, contacts, resource, from, to);
		  this.contacts = (List<Contact>) contacts;
		}

		/*		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
		  View view = super.getView(position, convertView, parent);

		  int colorPos = position % colors.length;
		  view.setBackgroundColor(colors[colorPos]);
		  return view;
		}
		*/
		
		}
	
	/*
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.  This
        // sample only has one Loader, so we don't care about the ID.
        // First, pick the base URI to use depending on whether we are
        // currently filtering.
        Uri baseUri;
        
            baseUri = People.CONTENT_URI;
            
        

        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        String select = "((" + PeopleColumns.DISPLAY_NAME + " NOTNULL) AND ("
                + PeopleColumns.DISPLAY_NAME + " != '' ))";
        return new CursorLoader(getActivity(), baseUri,
                CONTACTS_SUMMARY_PROJECTION, select, null,
                PeopleColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    }

    @Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // Swap the new cursor in.  (The framework will take care of closing the
        // old cursor once we return.)
        locations.swapCursor(data);

        // The list should now be shown.
        if (isResumed()) {
            setListShown(true);
        } else {
            setListShownNoAnimation(true);
        }
    }

    @Override
	public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
        locations.swapCursor(null);
    }
*/	 		  	
}
